package com.qf.j2112.controller;

import com.alibaba.fastjson.JSON;
import com.qf.j2112.anno.JWTAnno;
import com.qf.j2112.mapper.AddressMapper;
import com.qf.j2112.po.Cart;
import com.qf.j2112.po.Order;
import com.qf.j2112.po.OrderItem;
import com.qf.j2112.po.TourArea;
import com.qf.j2112.service.CartService;
import com.qf.j2112.service.OrderService;
import com.qf.j2112.service.TourAreaService;
import com.qf.j2112.utils.*;
import com.qf.j2112.vo.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private TourAreaService tourAreaService;

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private CartService cartService;

    @JWTAnno(name = "用户查询订单列表")
    @PostMapping("/getOrder")
    public ClientActionResultVo getOrderList(@RequestBody OrderVo orderVo ){
        String url= "http://8g878c.natappfree.cc";
        ClientActionResultVo actionResultVo = new ClientActionResultVo();
        String uid = orderVo.getToken();
        String usrInfoFromToken = JwtUtil.getUsrInfoFromToken(uid);
        List<Order> allOrder = orderService.findAllOrder(Integer.parseInt(usrInfoFromToken));
        if (allOrder!=null){
            List<ClientOrderVo> clientOrderVos = new ArrayList<>();
            for (Order order : allOrder) {
                List<OrderItem> allOrderItem = orderService.findAllOrderItem(order.getOrderId());
                ClientOrderVo clientOrderVo = new ClientOrderVo();
                List<GoodsItemsVo> goodsItemsVos = new ArrayList<>();
                for (OrderItem orderItem : allOrderItem) {
                    TourArea oneByAid = tourAreaService.findOneByAid(orderItem.getA_id());
                    GoodsItemsVo goodsItemsVo = GoodItemsUtil.itemsVo(oneByAid);
                    goodsItemsVo.setGoodOrderCount(orderItem.getItem_num());
                    goodsItemsVos.add(goodsItemsVo);
                }
                clientOrderVo.setAddressName(addressMapper.findOne(order.getAddrId()).getAddressidName());
                clientOrderVo.setCdk("https://api.pwmqr.com/qrcode/create/?url="+url+"/api/getTicket/?cdk="+order.getCdk());
                clientOrderVo.setIsPay(order.getIsPay());
                clientOrderVo.setGoods(goodsItemsVos);
                clientOrderVo.setOrderId(order.getOrderId());
                clientOrderVo.setTotalMoney(order.getTotalMoney());
                clientOrderVo.setOut_trade_no(order.getOut_trade_no());
                clientOrderVos.add(clientOrderVo);
            }
            actionResultVo.setData(clientOrderVos);
            actionResultVo.setStatusCode(200);
            actionResultVo.setMsg("查询成功！");
        }else{
            actionResultVo.setMsg("用户名下没有任何订单!");
            actionResultVo.setStatusCode(-200);
        }
        return actionResultVo;
    }

    @Transactional
    @JWTAnno(name = "用户创建订单")
    @PostMapping("/createOrder")
    //{addressId: 3, goods: "[{"goodcount":2,"goodid":6}]", totalMoney: 176,…}
    public ClientActionResultVo creatOrder(@RequestBody OrderVo orderVo ){
        ClientActionResultVo clientActionResultVo = new ClientActionResultVo();
        Order order = new Order();
        order.setAddrId(orderVo.getAddressId());
        order.setCdk(UuidUtil.generateShortUuid());
        order.setCreateTime(new Date());
        order.setTotalMoney(orderVo.getTotalMoney());
        int uid = Integer.parseInt(JwtUtil.getUsrInfoFromToken(orderVo.getToken()));
        order.setUid(uid);
        order.setOut_trade_no(OrderUtil.getOrderCode(uid));
        Order order1 = orderService.addOneOrder(order);

        String ord = (String)orderVo.getGoods();
        List<OrderVvo> goodsItemsVos= (List<OrderVvo>)JSON.parseArray(ord,OrderVvo.class);

        try{
            for (OrderVvo good : goodsItemsVos) {
                OrderItem orderItem = new OrderItem();
                orderItem.setOid(order1.getOrderId());
                orderItem.setA_id(good.getGoodid());
                orderItem.setItem_num(good.getGoodcount());

                //存入订单详情表
                orderService.addOneItem(orderItem);

                //减库存
                TourArea tourArea=tourAreaService.findOneByAid(good.getGoodid());
                tourArea.setCount(tourArea.getCount()-good.getGoodcount());
                //更新数据库
                tourAreaService.updateTourArea(tourArea);
            }
            clientActionResultVo.setMsg("创建成功");
            clientActionResultVo.setStatusCode(200);

        }catch (Exception E){
            clientActionResultVo.setMsg("创建失败！");
            clientActionResultVo.setStatusCode(-200);
        }
        return clientActionResultVo;
    }

    @JWTAnno(name = "更改订单状态为已支付")
    @PostMapping("/getTrade")
    public ClientActionResultVo getTrade(@RequestBody OrderVo orderVo ){
        ClientActionResultVo clientActionResultVo = new ClientActionResultVo();
        int orderPay = orderService.isOrderPay(orderVo.getTrade());
        if (orderPay>-1){
            clientActionResultVo.setStatusCode(200);
            clientActionResultVo.setMsg("修改成功");
        }else{
            clientActionResultVo.setMsg("修改失败");
            clientActionResultVo.setStatusCode(-200);
        }
        return clientActionResultVo;
    }

    @JWTAnno(name = "管理员获取全部订单")
    @GetMapping("/orders")
    public ActionResultVO getOrders( PageUtil pageUtil) {
        ActionResultVO vo = null;
        List<Order> orderList = orderService.findAll(pageUtil);

        int num=orderService.countOrder();
        if (!ObjectUtils.isEmpty(orderList)) {
            vo = new ActionResultVO(200, "查询全部订单成功", orderList, num);
        } else {
            vo = new ActionResultVO(-200, "查询全部订失败", null);
        }
        return vo;
    }

    @JWTAnno(name = "用户取票")
    @GetMapping("/getTicket")
    public ModelAndView getTicket(String cdk) {
        ModelAndView modelAndView=new ModelAndView();
        int res=orderService.getOutTicket(cdk);
        if(res==1){
            modelAndView.addObject("info","验票成功");
        }else if(res==0){
            modelAndView.addObject("info","数据更新失败，请重试");
        }else if(res==-1){
            modelAndView.addObject("info","订单状态异常,验票失败");
        }
        Order order=orderService.findOrderByCdk(cdk);
        modelAndView.addObject("order",order);
        modelAndView.setViewName("ticket");
        return modelAndView;
    }

}
